/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.xiongda.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.xiongda.entity.XComment;
import com.jeeplus.modules.xiongda.service.XCommentService;

/**
 * 评论Controller
 * @author 缪琼
 * @version 2017-11-29
 */
@Controller
@RequestMapping(value = "${adminPath}/xiongda/xComment")
public class XCommentController extends BaseController {

	@Autowired
	private XCommentService xCommentService;
	
	@ModelAttribute
	public XComment get(@RequestParam(required=false) String id) {
		XComment entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = xCommentService.get(id);
		}
		if (entity == null){
			entity = new XComment();
		}
		return entity;
	}
	
	/**
	 * 评论列表页面
	 */
	@RequiresPermissions("xiongda:xComment:list")
	@RequestMapping(value = {"list", ""})
	public String list(XComment xComment, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<XComment> page = xCommentService.findPage(new Page<XComment>(request, response), xComment); 
		model.addAttribute("page", page);
		return "modules/xiongda/xCommentList";
	}

	/**
	 * 查看，增加，编辑评论表单页面
	 */
	@RequiresPermissions(value={"xiongda:xComment:view","xiongda:xComment:add","xiongda:xComment:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(XComment xComment, Model model) {
		String userName = xCommentService.findUser(xComment.getUser().getId());
		xComment.getUser().setUserName(userName);
		model.addAttribute("xComment", xComment);
		return "modules/xiongda/xCommentForm";
	}

	/**
	 * 保存评论
	 */
	@RequiresPermissions(value={"xiongda:xComment:add","xiongda:xComment:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(XComment xComment, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, xComment)){
			return form(xComment, model);
		}
		if(!xComment.getIsNewRecord()){//编辑表单保存
			XComment t = xCommentService.get(xComment.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(xComment, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			xCommentService.save(t);//保存
		}else{//新增表单保存
			xCommentService.save(xComment);//保存
		}
		addMessage(redirectAttributes, "保存评论成功");
		return "redirect:"+Global.getAdminPath()+"/xiongda/xComment/?repage";
	}
	
	/**
	 * 删除评论
	 */
	@RequiresPermissions("xiongda:xComment:del")
	@RequestMapping(value = "delete")
	public String delete(XComment xComment, RedirectAttributes redirectAttributes) {
		xCommentService.deleteByLogic(xComment);
		addMessage(redirectAttributes, "删除评论成功");
		return "redirect:"+Global.getAdminPath()+"/xiongda/xComment/?repage";
	}
	
	/**
	 * 批量删除评论
	 */
	@RequiresPermissions("xiongda:xComment:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			xCommentService.delete(xCommentService.get(id));
		}
		addMessage(redirectAttributes, "删除评论成功");
		return "redirect:"+Global.getAdminPath()+"/xiongda/xComment/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("xiongda:xComment:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(XComment xComment, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "评论"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<XComment> page = xCommentService.findPage(new Page<XComment>(request, response, -1), xComment);
    		new ExportExcel("评论", XComment.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出评论记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/xiongda/xComment/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("xiongda:xComment:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<XComment> list = ei.getDataList(XComment.class);
			for (XComment xComment : list){
				try{
					xCommentService.save(xComment);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条评论记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条评论记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入评论失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/xiongda/xComment/?repage";
    }
	
	/**
	 * 下载导入评论数据模板
	 */
	@RequiresPermissions("xiongda:xComment:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "评论数据导入模板.xlsx";
    		List<XComment> list = Lists.newArrayList(); 
    		new ExportExcel("评论数据", XComment.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/xiongda/xComment/?repage";
    }
	
	
	

}